// 使用 RAII 等待线程终结
#include <iostream>
#include <thread>

class thread_gurad
{
private:
    std::thread &m_thread;

public:
    explicit thread_gurad(std::thread &thread) : m_thread(thread) {}
    ~thread_gurad()
    {
        if (m_thread.joinable())
        {
            m_thread.join();
        }
    }
    thread_gurad(thread_gurad const &) = delete;
    thread_gurad &operator=(thread_gurad const &) = delete;
};


void do_something(const int &i)
{
    std::cout << " do something " << i << std::endl;
}


struct func
{
    int &m_i;
    func(int &i) : m_i(i) {}
    void operator()()
    {
        for (unsigned j = 0; j < 100; j++)
        {
            do_something(j);
        }
    }
};


void do_something_in_current_thread()
{
    std::cout <<"thrad id: "<< std::this_thread::get_id() << std::endl;
}


void f()
{
    int some_local_state = 0;
    func my_func(some_local_state);
    std::thread my_thread(my_func);
    thread_gurad g(my_thread);

    do_something_in_current_thread();
}


int main()
{
    // f();

    int some_local_state = 0;
    func my_func(some_local_state);
    std::thread my_thread(my_func);
    thread_gurad g(my_thread);

    do_something_in_current_thread();

    return 0;
}